<template>
  <div>
    <el-card>
      <el-tabs>
        <el-tab-pane label="平台支出">
          <query-form :shop-query-list="platExpenses.shopQueryList" :page-data="platExpenses.pageData" :is-income="false" @query-expense-data="refreshTableData($event,false)" />
          <div class="add-btn">
            <el-button type="primary" @click="goAdd(false)">
              <i class="el-icon-plus" />
              新增
            </el-button>
          </div>
          <el-table :data="platExpenses.tableData">
            <el-table-column type="selection" />
            <el-table-column label="交易类型" prop="tradeType" />
            <el-table-column label="店铺名/用户名">
              <template #default="{ row }">
                {{ row.shopName }} / {{ row.userName }}
              </template>
            </el-table-column>
            <el-table-column label="单号" prop="order" />
            <el-table-column label="交易金额/元" prop="tsAmount" />
            <el-table-column label="交易时间" prop="date">
              <template #default="{row}">
                {{ row.date|formatDate }}
              </template>
            </el-table-column>
            <el-table-column label="确认退款率">
              <template #default="{row}">
                <el-button type="primary" size="mini" @click="goEdit(row,false)">编辑</el-button>
                <el-popconfirm
                  confirm-button-text="好的"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  :title="'确定要删除'+row.order+'吗？'"
                  @onConfirm="onDel(row.id,false)"
                  @onCancel="onDel(row.id,false)"
                >
                  <el-button slot="reference" type="danger" size="mini">删除</el-button>
                </el-popconfirm>
                <el-button type="infor" size="mini">溯源分析</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="center">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="platExpenses.total"
              :current-page="platExpenses.pageData._page"
              :page-sizes="[1, 3, 5, 7]"
              :page-size="platExpenses.pageData._limit"
              @size-change="handleSizeChange($event,false)"
              @current-change="handleCurrentChange($event,false)"
            />
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="平台收入">
          <query-form :shop-query-list="platIncome.shopQueryList" :page-data="platIncome.pageData" :is-income="true" @query-income-data="refreshTableData($event,true)" />
          <div class="add-btn">
            <el-button type="primary" @click="goAdd(true)">
              <i class="el-icon-plus" />
              新增
            </el-button>
          </div>
          <el-table :data="platIncome.tableData" style="width: 100%">
            <el-table-column type="selection" />
            <el-table-column label="交易类型" width="150px" prop="tradeType" />
            <el-table-column label="店铺名">
              <template #default="{ row }">
                {{ row.shopName }}
              </template>
            </el-table-column>
            <el-table-column label="单号" prop="order" />
            <el-table-column label="抽佣金" prop="brokerage" />
            <el-table-column label="平台收益/元" prop="profit" />
            <el-table-column label="交易金额/元" prop="tsAmount" />
            <el-table-column label="交易时间" prop="date">
              <template #default="{row}">
                {{ row.date|formatDate }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250px">
              <template #default="{row}">
                <el-button type="primary" size="mini" @click="goEdit(row,true)">编辑</el-button>
                <el-popconfirm
                  confirm-button-text="好的"
                  cancel-button-text="不用了"
                  icon="el-icon-info"
                  icon-color="red"
                  :title="'确定要删除'+row.order+'吗？'"
                  @onConfirm="onDel(row.id,true)"
                >
                  <el-button slot="reference" type="danger" size="mini">删除</el-button>
                </el-popconfirm>
                <el-button type="infor" size="mini">溯源分析</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="center">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="platIncome.total"
              :current-page="platIncome.pageData._page"
              :page-sizes="[1, 3, 5, 7]"
              :page-size="platIncome.pageData._limit"
              @size-change="handleSizeChange($event,true)"
              @current-change="handleCurrentChange($event,true)"
            />
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="isAdd?'新增交易记录':'编辑交易记录'" :visible.sync="isDialogShow" width="40%" @close="onCancel">
      <el-form ref="tsRecord" label-width="80px" :rules="formRules" :model="tsRecordForm">
        <el-form-item label="交易类型" prop="tradeType">
          <el-select v-model="tsRecordForm.tradeType" placeholder="请选择" style="width:100%">
            <el-option v-for="(item,i) in tradeTypeList" :key="i" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择店铺" prop="shopName">
          <el-select v-model="tsRecordForm.shopName" placeholder="请选择" style="width:100%">
            <el-option v-for="(item,i) in shopNameList" :key="i" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isIncome" label="选择用户" prop="userName">
          <el-select v-model="tsRecordForm.userName" placeholder="请选择" style="width:100%">
            <el-option v-for="(item,i) in userNameList" :key="i" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isIncome" label="抽佣金" prop="brokerage">
          <el-select v-model="tsRecordForm.brokerage" placeholder="请选择" style="width:100%">
            <el-option v-for="(item,i) in brokerageList" :key="i" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="额度" prop="tsAmount">
          <el-input v-model="tsRecordForm.tsAmount" />
        </el-form-item>
        <el-form-item v-if="isIncome" label="平台收益" prop="profit">
          <el-input v-model="tsRecordForm.profit " />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-row type="flex" justify="end">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import queryForm from './components/query-form'
import { getExpenseList, getIncomeList, delExpenseData, addExpenseData, editExpenseData, delIncomeData, addIncomeData, editIncomeData } from '@/api/platform'
import { formatDate } from '@/filters'
export default {
  name: 'IncomeAndExpenses',
  components: {
    queryForm
  },
  filters: {
    formatDate
  },
  data() {
    return {
      platIncome: {
        // shopQueryList: {
        //   shopName: '',
        //   userName: '',
        //   tradeType: '',
        //   order: '',
        //   date: ''
        // },
        shopQueryList: {
        },
        // tableData: [
        //   {
        //     tradeType: '', // 交易类型
        //     shopName: '', // 店铺名
        //     order: '', // 单号
        //     commission: '', // 抽佣金
        //     income: '', // 平台收益
        //     tsAmount: '', // 交易金额
        //     date: new Date() // 交易时间
        //   }
        // ],
        // userNameList: [],
        // shopNameList: [],
        tableData: [],
        pageData: {
          _page: 1,
          _limit: 3
        },
        total: 1
      },
      platExpenses: {
        shopQueryList: {
          shopName: '',
          userName: '',
          tradeType: '',
          withdrawOrder: '',
          date: ''
        },
        // tableData: [
        //   {
        //     tradeType: '', // 交易类型
        //     shopName: '', // 店铺名
        //     userName: '', // 用户名
        //     order: '', // 单号
        //     tsAmount: '', // 交易金额
        //     date: '' // 交易时间
        //   }
        // ],
        userNameList: [],
        shopNameList: [],
        tableData: [],
        pageData: {
          _page: 1,
          _limit: 3
        },
        total: 1
      },
      isDialogShow: false,
      isIncome: true,
      isAdd: true,
      tsRecordForm: {
        tradeType: '', // 交易类型
        shopName: '', // 商铺名称
        userName: '', // 用户名称
        tsAmount: '', // 额度
        brokerage: '', // 抽佣金
        profit: '', // 平台收益
        date: '',
        order: ''
      },
      formRules: {
        tradeType: [
          { required: true, message: '交易类型不能为空', trriger: 'input' }
        ],
        shopName: [
          { required: true, message: '店铺名不能为空', trriger: 'blur' }
        ],
        userName: [
          { required: true, message: '用户名不能为空', trriger: 'blur' }
        ],
        brokerage: [
          { required: true, message: '抽佣金不能为空', trriger: 'change' }
        ],
        tsAmount: [
          { required: true, message: '交易金额不能为空', trriger: 'blur' }
        ],
        profit: [
          { required: true, message: '收益不能为空', trriger: 'blur' }
        ]
      },
      tradeTypeList: [
        '现金付款',
        '刷储蓄卡支付',
        '刷信用卡支付',
        '微信付款',
        '支付宝'
      ],
      shopNameList: [
        '高杰的商铺',
        '谢秀英的商铺',
        '董强的商铺',
        '于丽的商铺',
        '程洋的商铺',
        '尹秀英的商铺',
        '彭伟的商铺',
        '钱秀英的商铺',
        '叶芳的商铺',
        '杨超的商铺'
      ],
      userNameList: ['潘艳',
        '程磊',
        '彭静',
        '许磊',
        '罗芳',
        '郝强',
        '赖静',
        '雷秀英',
        '邱敏',
        '唐平'],
      brokerageList: ['3%', '7%', '10%']
    }
  },
  async created() {
    this.getExpenseList()
    this.getIncomeList()
  },
  methods: {
    async getExpenseList() {
      const { data } = await getExpenseList(this.platExpenses.pageData)
      if (data.data.length === 0 && this.platExpenses.pageData._page !== 1) {
        console.log(data.data.length, this.platExpenses.pageData._page)
        this.platExpenses.pageData._page--
        this.getExpenseList()
      } else {
        this.platExpenses.tableData = data.data
        // 数组去重
        // const userNameList = data.data.map(item => item.userName)
        // this.platExpenses.userNameList = Array.from(new Set(userNameList))
        this.platExpenses.total = data.total
        console.log(data.data)
      }
    },
    async getIncomeList() {
      const { data } = await getIncomeList(this.platIncome.pageData)
      if (data.data.length === 0 && this.platIncome.pageData._page !== 1) {
        this.platIncome.pageData._page--
        this.getIncomeList()
      } else {
        this.platIncome.tableData = data.data
        this.platIncome.total = data.total
      }
    },
    handleCurrentChange(page, isIncome) {
      if (isIncome) {
        this.platIncome.pageData._page = page
        this.getIncomeList()
      } else {
        this.platExpenses.pageData._page = page
        this.getExpenseList()
      }
    },
    handleSizeChange(limit, isIncome) {
      console.log(limit, isIncome)
      if (isIncome) {
        this.platIncome.pageData._limit = limit
        this.getIncomeList()
      } else {
        this.platExpenses.pageData._limit = limit
        this.getExpenseList()
      }
    },
    async onDel(uid, isIncome) {
      if (isIncome) {
        const res = await delIncomeData(uid)
        console.log(res)
        this.getIncomeList()
      } else {
        await delExpenseData(uid)
        this.getExpenseList()
      }
    },
    goAdd(isIncome) {
      this.isIncome = isIncome
      this.isAdd = true
      this.isDialogShow = true
    },
    goEdit(row, isIncome) {
      this.isIncome = isIncome
      this.tsRecordForm = row
      this.$nextTick().then(() => { this.isDialogShow = true })
    },
    onCancel() {
      this.isDialogShow = false
      this.tsRecordForm = {
        tradeType: '',
        shopName: '',
        userName: '',
        tsAmount: '',
        brokerage: '',
        profit: '',
        date: '',
        order: ''
      }
      this.$refs.tsRecord.resetFields()
    },
    onSubmit() {
      try {
        this.$refs.tsRecord.validate().then(async() => {
          this.tsRecordForm.order = 'A' + parseInt(1000000 * Math.random())
          this.tsRecordForm.date = new Date()
          if (this.isIncome) {
            if (this.tsRecordForm.id) {
              console.log(this.tsRecordForm)
              await editIncomeData(this.tsRecordForm)
              this.$message.success('修改成功')
            } else {
              await addIncomeData(this.tsRecordForm)
              this.$message.success('添加成功')
            }
          } else {
            if (this.tsRecordForm.id) {
              console.log(this.tsRecordForm)
              await editExpenseData(this.tsRecordForm)
              this.$message.success('修改成功')
            } else {
              await addExpenseData(this.tsRecordForm)
              this.$message.success('添加成功')
            }
          }
          this.getExpenseList()
          this.isDialogShow = false
          this.$refs.tsRecord.resetFields()
        })
      } catch (err) {
        console.log(err)
      }
    },
    refreshTableData(data, isIncome) {
      if (!isIncome) {
        this.platExpenses.tableData = data
        this.platExpenses.total = data.length
        console.log(this.platExpenses.tableData, '触发了')
      } else {
        this.platIncome.tableData = data
        this.platIncome.total = data.length
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-btn {
  padding-bottom: 20px;
}
.el-pagination {
  padding-top: 30px;
}
</style>
